<script setup lang="ts">
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import "plus-pro-components/es/components/search/style/css";
import EChartsComponent from "@/components/EChartsComponent/index.vue";
import { PaginationProps } from "@pureadmin/table";
import { getDataBySQLDesc } from "@/api/common";
import { computed, onMounted, h, reactive, ref } from "vue";
import { ElInput, ElTreeSelect } from "element-plus";
defineOptions({
  name: "WorkingHoursForBOM"
});
const loading = ref(false);
const allProductData = ref([]);
const form = ref({
  cxnd: "",
  plbh: ""
});
const yearForm = ref({
  jgdzt: "",
  ljlb: ""
});
const monthForm = ref({
  jgdzt: "",
  ljlb: ""
});
const option = ref({
  title: {
    text: "BOM应用平均用时"
  },
  tooltip: {
    trigger: "axis",
    position: function (point, params, dom, rect, size) {
      // point: 鼠标位置，格式为 [x, y]
      // params: 提示框所包含的数据信息
      // dom: 提示框的 DOM 元素
      // rect: 鼠标所在图形的包围盒，格式为 {x, y, width, height}
      // size: 提示框的大小，格式为 {contentSize: [width, height], outerSize: [width, height]}
      return [point[0] - 50, point[1] - 50]; // 设置提示框在鼠标上方 20px 处
    },
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999"
      }
    }
  },
  legend: {
    type: "scroll",
    right: 10,
    data: ["BOM制作平均用时"]
  },
  xAxis: [
    {
      type: "category",
      data: [],
      axisPointer: {
        type: "shadow"
      }
    }
  ],
  yAxis: [
    {
      type: "value",
      name: "分钟",
      axisLabel: {
        formatter: "{value}"
      }
    }
  ],
  series: [
    {
      name: "BOM制作平均用时",
      type: "bar",
      yAxisIndex: 0,
      tooltip: {
        valueFormatter: function (value) {
          return value;
        }
      },
      data: []
    }
  ]
});
const searchColumns = computed<PlusColumn[]>(() => [
  {
    label: "审核时间",
    prop: "cxnd",
    valueType: "date-picker",
    fieldProps: {
      type: "year",
      valueFormat: "YYYY",
      placeholder: "请选择审核时间"
    }
  },
  {
    label: "成品品类",
    prop: "plbh",
    valueType: "cascader",
    fieldProps: {
      placeholder: "请选择成品品类"
    },
    renderField(value, onChange) {
      return h(ElTreeSelect as any, {
        data: supplierOptions.value.data,
        filterable: true,
        clearable: true,
        checkStrictly: true,
        modelValue: form.value.plbh,
        "onUpdate:modelValue": (val: any) => {
          onChange && onChange(val); // 同步调用 onChange 逻辑
        }
      });
    }
  }
]);
/** 分页配置 */
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default",
  layout: "prev, pager, next"
});
const tableData = ref([]);
const columns = computed(() => [
  {
    prop: "姓名",
    label: "人员"
  },
  {
    prop: "1月平均制作用时",
    label: form.value.cxnd + "年1月"
  },
  {
    prop: "2月平均制作用时",
    label: form.value.cxnd + "年2月"
  },
  {
    prop: "3月平均制作用时",
    label: form.value.cxnd + "年3月"
  },
  {
    prop: "4月平均制作用时",
    label: form.value.cxnd + "年4月"
  },
  {
    prop: "5月平均制作用时",
    label: form.value.cxnd + "年5月"
  },
  {
    prop: "6月平均制作用时",
    label: form.value.cxnd + "年6月"
  },
  {
    prop: "7月平均制作用时",
    label: form.value.cxnd + "年7月"
  },
  {
    prop: "8月平均制作用时",
    label: form.value.cxnd + "年8月"
  },
  {
    prop: "9月平均制作用时",
    label: form.value.cxnd + "年9月"
  },
  {
    prop: "10月平均制作用时",
    label: form.value.cxnd + "年10月"
  },
  {
    prop: "11月平均制作用时",
    label: form.value.cxnd + "年11月"
  },
  {
    prop: "12月平均制作用时",
    label: form.value.cxnd + "年12月"
  },
  {
    prop: "年平均制作用时",
    label: "年度平均"
  }
]);
const handleSearch = async () => {
  const product = allProductData.value.find(item => {
    return item["品类编号"] == form.value.plbh;
  });
  option.value.title.text = `${form.value.cxnd}年度${product ? product["品类名称"] : ""}BOM应用平均用时`;
  getChartsData();
  getTableData();
};
const getTime = async () => {
  const { data } = await getDataBySQLDesc({
    action: "public/get_server_sysdate"
  });
  form.value.cxnd = data[0].年;
  option.value.title.text = `${form.value.cxnd}年度BOM应用平均用时`;
  getAllParams();
};
const getChartsData = async () => {
  let params = {
    action: "biz/reports/get_cts_bom_pjys_by_year",
    plbh: form.value.plbh,
    cxnd: form.value.cxnd,
    jgdzt: yearForm.value.jgdzt,
    ljlb: yearForm.value.ljlb
  };
  const { data } = await getDataBySQLDesc(params);
  option.value.xAxis[0].data = data.map(item => item.姓名);
  option.value.series[0].data = data.map(item => item.平均制作用时);
};
const getTableData = async () => {
  let params = {
    action: "biz/reports/get_cts_bom_pjys_by_month",
    plbh: form.value.plbh,
    cxnd: form.value.cxnd,
    jgdzt: monthForm.value.jgdzt,
    ljlb: monthForm.value.ljlb
  };
  const { data } = await getDataBySQLDesc(params);
  tableData.value = data;
};
const supplierOptions = ref({
  data: []
});
// 定义辅助函数来构建树状结构
const buildTree = (items: any[], parentId = "") => {
  return items
    .filter(item => item["父品类编码"] === parentId)
    .map(item => ({
      ...item,
      label: item["品类名称"],
      value: item["品类编号"],
      children: buildTree(items, item["品类编号"])
    }));
};
const getFinishedProductCategoryTree = async () => {
  const { data } = await getDataBySQLDesc({
    action: "public/get_finished_product_category_tree"
  });
  allProductData.value = data;
  supplierOptions.value.data = buildTree(data);
  form.value.plbh = data.find(el => el["层级"] === "1")["品类编号"];
};

const handleRest = () => {
  form.value.plbh = allProductData.value.find(el => el["层级"] === "1")[
    "品类编号"
  ];
  getTime();
};
const getAllParams = async () => {
  let yearParams = {
    action: "public/get_bi_sjfw",
    hsmc: "get_cts_bom_pjys_by_year"
  };
  let monthParams = {
    action: "public/get_bi_sjfw",
    hsmc: "get_cts_bom_pjys_by_month"
  };
  const { data: yearData } = await getDataBySQLDesc(yearParams);
  const { data: monthData } = await getDataBySQLDesc(monthParams);
  yearData.map(e => {
    yearForm.value[e["参数编码"]] = e["参数值"];
  });
  monthData.map(e => {
    monthForm.value[e["参数编码"]] = e["参数值"];
  });
  handleSearch();
};
onMounted(async () => {
  await getFinishedProductCategoryTree();
  getTime();
});
</script>

<template>
  <div class="page-content">
    <el-card>
      <PlusSearch
        v-model="form"
        searchText="搜索"
        resetText="重置"
        expand-text="展开"
        retractText="收起"
        :columns="searchColumns"
        :show-number="2"
        label-width="80"
        label-position="right"
        @search="handleSearch"
        @reset="handleRest"
      />
    </el-card>
    <el-card class="chart-card mt-[20px]">
      <div class="chart bar-chart">
        <EChartsComponent :extraOptions="option" type="bar" />
      </div>
    </el-card>
    <el-card class="table-card">
      <div class="operate">
        <el-button type="primary">导出</el-button>
      </div>
      <PureTable
        ref="tableRef"
        :loading="loading"
        border
        row-key="id"
        alignWhole="center"
        showOverflowTooltip
        :data="tableData"
        :columns="columns"
        :pagination="pagination"
      />
    </el-card>
  </div>
</template>
<style lang="css" scoped>
.table-card {
  margin-top: 20px;
}

.operate {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}
</style>
